package com.codingfuture.erp_system.web.controller;

import com.codingfuture.erp_system.dto.DepDto;
import com.codingfuture.erp_system.dto.PageData;
import com.codingfuture.erp_system.entity.Dep;
import com.codingfuture.erp_system.service.DepService;
import com.codingfuture.erp_system.util.CheckUtils;
import com.codingfuture.erp_system.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RequestMapping("/v2")
@RestController


public class DepController {

    @Autowired
    private DepService depService;
    private final String str = "";

    //添加
    @PostMapping("/dep/add")
    public Result insert(Dep dep) {
        String name = dep.getName();
        if (name == null || name.equals(str)) {
            return Result.error(400, "请正确输入");
        }
        //校验联系电话
        else if (CheckUtils.checkMobile(dep.getTele())) {
            return Result.error(500, "联系电话格式不正确");
        } else if (depService.nameExist(name) == null) {
            boolean result = depService.insert(dep);
            return result ? Result.ok() : Result.error(500, "添加失败");
        }
        return Result.error(400, "部门名称重复，请重新输入");

    }

    //全部数据
    @GetMapping("/dep/listByPage")
    public Result findByAll(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "10") int rows,
                            Dep dep) {
        Page<Dep> page1 = PageHelper.startPage(page, rows);
        List<Dep> List = depService.findByAll(dep);
        PageData<Dep> data = new PageData<>(List, page1.getTotal());
        return Result.ok(data);
    }

    // id查询
    @GetMapping("/dep/selectone")
    public Result findById(Integer id, HttpSession session) {
        session.setAttribute("depId", id);
        DepDto depDto = depService.findById(id);
        return depDto != null ?
                Result.OK(depDto) :
                Result.error(500, "服务器错误");
    }

    //编辑
    @PostMapping("/dep/update")
    public Result update(Dep dep, HttpSession session) {
        Object id = session.getAttribute("depId");
        dep.setUuid((Integer) id);
        String name = dep.getName();
        if (name == null || name.equals(str)) {
            return Result.error(400, "请正确输入");
        }//校验联系电话
        else if (CheckUtils.checkMobile(dep.getTele())) {
            return Result.error(500, "联系电话格式不正确");
        } else if (depService.nameExist(name) == null) {
            boolean result = depService.update(dep);
            return result ? Result.ok() : Result.error(500, "失败");
        }

        return Result.error(400, "部门重复，请重新输入");
    }

    //删除
    @DeleteMapping("/dep")
    public Result delete(Integer id) {
        depService.delete(id);
        return Result.ok();
    }

}
